package App.Service;

import App.Model.Chat.GroupResponse;
import App.Model.Tecent.IMGroupMember;
import App.Model.Tecent.IMGroupMemberAdd;
import App.Model.Tecent.TecentIMConfig;
import App.Repository.TecentIMRepository;
import App.Tencent.SignatureManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by xw on 2018/12/4.
 * 调用云通讯接口
 * 创建聊天组
 * 添加聊天组成员
 */

@Component
public class TecentIMService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private TecentIMConfig _imConfig;

    @Autowired
    private TecentIMRepository _repository;

    private Random rand = new Random(99999999);

    //测试获取群组
    public String queryGroups(List GroupIdList){
        int _adminId = getAdminId();
        long _sdkid = getSDKId();
        String _winKeyPath = getWinKeyPath();
        String _linuxKeyPath = getLinuxKeyPath();
//        String _method ="group_open_http_svc/get_appid_group_list";
        String _method ="group_open_http_svc/get_group_info";
        String _sig = SignatureManager.getSignatureAdv(_sdkid, _winKeyPath, _linuxKeyPath, Integer.toString(_adminId), _imConfig.getSigType(), _imConfig.getSecuretKey());
        String _url = getUrl(_sig, _method, _adminId);
        //请求数据
        JSONObject postData = new JSONObject();
        postData.put("GroupIdList",GroupIdList);
        ResponseEntity<String> _callReponse = restTemplate.postForEntity(_url, postData, String.class);
        String _responseBody = _callReponse.getBody();
        logger.info(_responseBody);
        return _responseBody;
    }

    //注册账号成功
    public boolean accountImport(int userid, String realName) {
        boolean isSuccess = false;
        try {

            long _sdkid = getSDKId();
            String _winKeyPath = getWinKeyPath();
            String _linuxKeyPath = getLinuxKeyPath();

            //需要用管理员权限的id,才可以导入用户
            int adminid = getAdminId();
            String strUserid = Integer.toString(userid);
            String _method = getAccountUrl() + getAccountImportMethod();
            String _sig = SignatureManager.getSignatureAdv(_sdkid, _winKeyPath, _linuxKeyPath, Integer.toString(adminid), _imConfig.getSigType(), _imConfig.getSecuretKey());
            String _url = getUrl(_sig, _method, adminid);

            JSONObject _postData = new JSONObject();
            _postData.put("Identifier", strUserid);
            _postData.put("Nick", realName);
            _postData.put("FaceUrl", "");


            ResponseEntity<String> _callReponse = restTemplate.postForEntity(_url, _postData, String.class);
            System.out.println("account import response:" + _callReponse);

            String _responseBody = _callReponse.getBody();
            GroupResponse _groupResponse = JSON.parseObject(_responseBody, GroupResponse.class);
            String _actionStatus = _groupResponse.getActionStatus();
            if (_actionStatus.equals("OK")) {
                isSuccess = true;
            }


            new Thread(() -> {
                String _requestString = JSON.toJSONString(_postData);
                _repository.insertIMHistory("注册账号", _url, _requestString, _responseBody);
            }).start();


        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return isSuccess;
    }

    private String getUrl(String sig, String method, int userid) {
        int random = rand.nextInt();
        long sdkid = getSDKId();
        String rootUrl = getRootUrl();

        return String.format("%s%s?usersig=%s&identifier=%s&sdkappid=%s&random=%s&contenttype=json", rootUrl, method, sig, userid, sdkid, random);
    }

    //  2022/4/15 失效账号登陆状态
    public boolean kickImUser(int userid) {
        boolean isSuccess = false;
        try {
            int _adminId = getAdminId();
            long _sdkid = getSDKId();
            String _winKeyPath = getWinKeyPath();
            String _linuxKeyPath = getLinuxKeyPath();

            String strUserid = Integer.toString(userid);
            String _method = getAccountUrl() + getKickMethod();

            String _sig = SignatureManager.getSignatureAdv(_sdkid, _winKeyPath, _linuxKeyPath, Integer.toString(_adminId), _imConfig.getSigType(), _imConfig.getSecuretKey());
            String _url = getUrl(_sig, _method, _adminId);
            //请求数据
            JSONObject _postData = new JSONObject();
            _postData.put("UserID", strUserid);
            logger.info("the request body:" + _postData.toString());
            ResponseEntity<String> _callReponse = restTemplate.postForEntity(_url, _postData, String.class);
            String _responseBody = _callReponse.getBody();
            logger.info("the response body:" + _responseBody);
            GroupResponse _groupResponse = JSON.parseObject(_responseBody, GroupResponse.class);
            String _actionStatus = _groupResponse.getActionStatus();
            if (_actionStatus.equals("OK")) {
                isSuccess = true;
            }
            new Thread(() -> {
                String _requestString = JSON.toJSONString(_postData);
                _repository.insertIMHistory("创建聊天组", _url, _requestString, _responseBody);
            }).start();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return isSuccess;
    }

    //创建聊天组
    public boolean createIMGroup(String groupid, String groupName, String groupIntroduction, int userid) {
        boolean isSuccess = false;
        try {

            int _adminId = getAdminId();
            long _sdkid = getSDKId();
            String _winKeyPath = getWinKeyPath();
            String _linuxKeyPath = getLinuxKeyPath();

            String strUserid = Integer.toString(userid);
            String _method = getGroupUrl() + getCreateGroupMethod();

            String _sig = SignatureManager.getSignatureAdv(_sdkid, _winKeyPath, _linuxKeyPath, Integer.toString(_adminId), _imConfig.getSigType(), _imConfig.getSecuretKey());
            String _url = getUrl(_sig, _method, _adminId);

            //请求数据
            JSONObject _postData = new JSONObject();
            _postData.put("Owner_Account", strUserid);
            _postData.put("Type", "Private");
            _postData.put("GroupId", groupid);
            _postData.put("Name", groupName);
            _postData.put("Introduction", groupIntroduction);

            logger.info("the request body:" + _postData.toString());
            ResponseEntity<String> _callReponse = restTemplate.postForEntity(_url, _postData, String.class);
            String _responseBody = _callReponse.getBody();
            // System.out.println("create response body:" + _responseBody);
            logger.info("the response body:" + _responseBody);
            GroupResponse _groupResponse = JSON.parseObject(_responseBody, GroupResponse.class);
            String _actionStatus = _groupResponse.getActionStatus();
            if (_actionStatus.equals("OK")) {
                isSuccess = true;
            }

            new Thread(() -> {
                String _requestString = JSON.toJSONString(_postData);
                _repository.insertIMHistory("创建聊天组", _url, _requestString, _responseBody);
            }).start();


        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return isSuccess;
    }

    //删除聊天组
    public boolean destroyIMGroup(String groupid, int userid) {
        boolean isSuccess = false;
        try {

            int _adminId = getAdminId();
            long sdkid = getSDKId();
            String _winKeyPath = getWinKeyPath();
            String _linuxKeyPaht = getLinuxKeyPath();

            String strUserid = Integer.toString(userid);
            String _method = getGroupUrl() + getDestroyGroupMethod();

            String _sig = SignatureManager.getSignatureAdv(sdkid, _winKeyPath, _linuxKeyPaht, Integer.toString(_adminId), _imConfig.getSigType(), _imConfig.getSecuretKey());
            String _url = getUrl(_sig, _method, _adminId);

            //请求数据
            JSONObject _postData = new JSONObject();
            _postData.put("GroupId", groupid);

            logger.info("the request body:" + _postData.toString());
            ResponseEntity<String> _callReponse = restTemplate.postForEntity(_url, _postData, String.class);
            String _responseBody = _callReponse.getBody();
            logger.info("the response body:" + _responseBody);
            GroupResponse _groupResponse = JSON.parseObject(_responseBody, GroupResponse.class);
            String _actionStatus = _groupResponse.getActionStatus();
            if (_actionStatus.equals("OK")) {
                isSuccess = true;
            }

            new Thread(() -> {
                String _requestString = JSON.toJSONString(_postData);
                _repository.insertIMHistory("删除聊天组", _url, _requestString, _responseBody);
            }).start();

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return isSuccess;
    }

    //添加聊天组成员
    public boolean addIMGroupMember(String groupid, List<Integer> members, int userid) {

        boolean isSuccess = false;
        try {

            int _adminId = getAdminId();
            long _sdkid = getSDKId();
            String _winKeyPath = getWinKeyPath();
            String _linuxKeyPath = getLinuxKeyPath();

            String _method = getGroupUrl() + getAddGroupMemberMethod();
            String _sig = SignatureManager.getSignatureAdv(_sdkid, _winKeyPath, _linuxKeyPath, Integer.toString(_adminId), _imConfig.getSigType(), _imConfig.getSecuretKey());
            String _url = getUrl(_sig, _method, _adminId);

            JSONObject _postData = new JSONObject();
            _postData.put("GroupId", groupid);
            _postData.put("Silence", 1);
            JSONArray jsonArray = new JSONArray();

            //请求数据
            IMGroupMemberAdd _addMemberRequest = new IMGroupMemberAdd();
            List<IMGroupMember> _memberList = new ArrayList<>();
            _addMemberRequest.setGroupId(groupid);
            for (Integer memberid : members) {
                JSONObject _memberObject = new JSONObject();
                _memberObject.put("Member_Account", Integer.toString(memberid));
                jsonArray.add(_memberObject);
            }
            _postData.put("MemberList", jsonArray);

            ResponseEntity<String> _callReponse = restTemplate.postForEntity(_url, _postData, String.class);
            String _responseBody = _callReponse.getBody();
            System.out.println("response data:" + _responseBody);
            JSONObject _responseJson = JSONObject.parseObject(_responseBody);
            String _okResult = _responseJson.get("ActionStatus").toString().trim();
            System.out.println("_okResult:" + _okResult);
            if (_okResult.equals("OK")) {
                isSuccess = true;
            }

            //new Thread(() -> {
            String _requestString = JSON.toJSONString(_postData);
            _repository.insertIMHistory("添加聊天组成员", _url, _requestString, _responseBody);
            //  }).start();


        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return isSuccess;
    }

    //移除聊天组成员
    public boolean removeIMGroupMember(String groupid, List<Integer> members, int userid) {
        boolean isSuccess = false;
        try {

            int _adminid = getAdminId();
            long sdkid = getSDKId();
            String _winKeyPath = getWinKeyPath();
            String _linuxKeyPaht = getLinuxKeyPath();

            String _method = getGroupUrl() + getDeleteGroupMemberMethod();
            String _sig = SignatureManager.getSignatureAdv(sdkid, _winKeyPath, _linuxKeyPaht, Integer.toString(_adminid), _imConfig.getSigType(), _imConfig.getSecuretKey());
            String _url = getUrl(_sig, _method, _adminid);

            JSONObject _postData = new JSONObject();
            _postData.put("GroupId", groupid);
            JSONArray jsonArray = new JSONArray();

            //请求数据
            IMGroupMemberAdd _addMemberRequest = new IMGroupMemberAdd();
            _addMemberRequest.setGroupId(groupid);
            for (Integer memberid : members) {
                jsonArray.add(Integer.toString(memberid));
            }
            _postData.put("MemberToDel_Account", jsonArray);

            ResponseEntity<String> _callReponse = restTemplate.postForEntity(_url, _postData, String.class);
            String _responseBody = _callReponse.getBody();
            System.out.println("response data:" + _responseBody);
            JSONObject _responseJson = JSONObject.parseObject(_responseBody);
            String _okResult = _responseJson.get("ActionStatus").toString().trim();
            System.out.println("_okResult:" + _okResult);
            if (_okResult.equals("OK")) {
                System.out.println(" remove the member is ok!");
                isSuccess = true;
            } else {
                System.out.println(" remove the member is not ok!");
            }

            new Thread(() -> {
                String _requestString = JSON.toJSONString(_postData);
                _repository.insertIMHistory("移除聊天组成员", _url, _requestString, _responseBody);
            }).start();


        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return isSuccess;
    }

    public String sendGrooupMessage(String groupid, String message, int userid) {

        boolean isSuccess = false;
        int _adminId = getAdminId();
        long _sdkid = getSDKId();
        String _winKeyPath = getWinKeyPath();
        String _linuxKeyPath = getLinuxKeyPath();

        String strUserid = Integer.toString(userid);
        String _method = getGroupUrl() + "send_group_system_notification";
        String _sig = SignatureManager.getSignatureAdv(_sdkid, _winKeyPath, _linuxKeyPath, Integer.toString(_adminId), _imConfig.getSigType(), _imConfig.getSecuretKey());
        String _url = getUrl(_sig, _method, _adminId);

        //请求数据
        JSONObject _postData = new JSONObject();
        _postData.put("GroupId", groupid);
        _postData.put("Content", "message");

        ResponseEntity<String> _callReponse = restTemplate.postForEntity(_url, _postData, String.class);
        String _responseBody = _callReponse.getBody();
        System.out.println("create response body:" + _responseBody);
        GroupResponse _groupResponse = JSON.parseObject(_responseBody, GroupResponse.class);
        String _actionStatus = _groupResponse.getActionStatus();
        if (_actionStatus.equals("OK")) {
            isSuccess = true;
        }

        new Thread(() -> {
            String _requestString = JSON.toJSONString(_postData);
            _repository.insertIMHistory("发送群通知", _url, _requestString, _responseBody);
        }).start();

        return _responseBody;
    }

    //外部调用的发送消息的方法, //  2022/3/19  添加pushFlag，groupName
    public String sendMessage(int pushFlag, String groupName, String groupid, String title, String message, String messageType, String extData, JSONObject extJsonObject, int userid) {
        return sendGrooupCommonMessage(pushFlag, groupName, groupid, title, message, messageType, extData, extJsonObject, null, userid);
    }
    public String sendMessage2(int pushFlag, String groupName, String groupid, String title, String message, String messageType, String extData, JSONObject extJsonObject, int userid) {
        return sendGrooupCommonMessage2(pushFlag, groupName, groupid, title, message, messageType, extData, extJsonObject, null, userid);
    }

    public String sendMessage(int pushFlag, String groupName, String groupid, String title, String message, String messageType, String extData, JSONObject extJsonObject, JSONObject custExtJsonObject, int userid) {
        return sendGrooupCommonMessage(pushFlag, groupName, groupid, title, message, messageType, extData, extJsonObject, custExtJsonObject, userid);
    }

    public String sendMessage(int pushFlag, String groupName, String groupid, String title, String message, String messageType, String extData, int userid) {
        return sendGrooupCommonMessage(pushFlag, groupName, groupid, title, message, messageType, extData, null, null, userid);
    }

    //send TIMTextElem  type message
    public String sendGrooupCommonMessage_old(String groupid, String message, int userid) {

        boolean isSuccess = false;
        int _adminId = getAdminId();
        long sdkid = getSDKId();
        String _winKeyPath = getWinKeyPath();
        String _linuxKeyPaht = getLinuxKeyPath();


        String strUserid = Integer.toString(userid);
        String _method = getGroupUrl() + getCommonGroupMessageMethod();
        String _sig = SignatureManager.getSignatureAdv(sdkid, _winKeyPath, _linuxKeyPaht, Integer.toString(_adminId), _imConfig.getSigType(), _imConfig.getSecuretKey());
        String _url = getUrl(_sig, _method, _adminId);

        //请求数据
        JSONObject _postData = new JSONObject();
        _postData.put("GroupId", groupid);
        _postData.put("Content", "message");


        JSONObject _content = new JSONObject();
        _content.put("Text", message);

        JSONObject _body = new JSONObject();
        _body.put("MsgType", "TIMTextElem");
        _body.put("MsgContent", _content);

        JSONArray _bodyArray = new JSONArray();
        _bodyArray.add(_body);

        int random = Math.abs(rand.nextInt());
        JSONObject _messageRequest = new JSONObject();
        _messageRequest.put("MsgBody", _bodyArray);
        _messageRequest.put("Random", random);
        _messageRequest.put("From_Account", "1");
        _messageRequest.put("GroupId", groupid);

        String _requestJson = _messageRequest.toJSONString();
        logger.info("the im push message request body:" + _requestJson);

        String _responseBody = "";
        if (isSendmessage()) {
            ResponseEntity<String> _callReponse = restTemplate.postForEntity(_url, _messageRequest, String.class);
            _responseBody = _callReponse.getBody();
            logger.info("the im push message response body:" + _responseBody);
            GroupResponse _groupResponse = JSON.parseObject(_responseBody, GroupResponse.class);
            String _actionStatus = _groupResponse.getActionStatus();
            if (_actionStatus.equals("OK")) {
                isSuccess = true;
            }

            String _requestString = JSON.toJSONString(_postData);
            _repository.insertIMHistory("发送群消息", _url, _requestString, _responseBody);
        }
        return _responseBody;
    }

    public String sendGrooupCommonMessage(int pushFlag, String groupName, String groupid, String title, String message, String messageType, String extData,
                                          JSONObject extJsonObject,
                                          JSONObject custExtJsonObject, int userid) {

        boolean isSuccess = false;
        int _adminId = getAdminId();
        long _sdkid = getSDKId();
        String _winKeyPath = getWinKeyPath();
        String _linuxKeyPath = getLinuxKeyPath();


        String strUserid = Integer.toString(userid);
        String _method = getGroupUrl() + getCommonGroupMessageMethod();
        String _sig = SignatureManager.getSignatureAdv(_sdkid, _winKeyPath, _linuxKeyPath, Integer.toString(_adminId), _imConfig.getSigType(), _imConfig.getSecuretKey());
        String _url = getUrl(_sig, _method, _adminId);

        //请求数据
        JSONObject _postData = new JSONObject();
        _postData.put("GroupId", groupid);
        _postData.put("Content", "message");

        /*
        *
        *    "MsgContent": {
        "Data": "发送消息的内容",  --群聊的内容
        "Desc": "消息的类型",      --消息的类型：text,file
        "Ext": "url",              --额外的数据，file类型就是文件的url
        "Sound": "dingdong.aiff"
    }
        * */
        JSONObject _contentText = new JSONObject();
        _contentText.put("Text", message);

        JSONObject _bodyText = new JSONObject();
        _bodyText.put("MsgType", "TIMTextElem");
        _bodyText.put("MsgContent", _contentText);

        JSONArray _bodyArray = new JSONArray();
        _bodyArray.add(_bodyText);

        if (custExtJsonObject != null) {
            JSONObject _extContent = new JSONObject();
            _extContent.put("Data", message);
            _extContent.put("Desc", "customermsg");
            _extContent.put("Ext", custExtJsonObject.toJSONString());

            JSONObject _extBody = new JSONObject();
            _extBody.put("MsgType", "TIMCustomElem");
            _extBody.put("MsgContent", _extContent);

            _bodyArray.add(_extBody);
        }

        if (extJsonObject != null) {
            JSONObject _extContent = new JSONObject();
            _extContent.put("Data", message);
            _extContent.put("Desc", "customer");
            _extContent.put("Ext", extJsonObject.toJSONString());

            JSONObject _extBody = new JSONObject();
            _extBody.put("MsgType", "TIMCustomElem");
            _extBody.put("MsgContent", _extContent);

            _bodyArray.add(_extBody);
        }

        JSONObject _content = new JSONObject();
        _content.put("Data", message);
        _content.put("Desc", "file");
        _content.put("Ext", extData);

        JSONObject _body = new JSONObject();
        _body.put("MsgType", "TIMCustomElem");
        _body.put("MsgContent", _content);
        if (messageType.equals("file")) {
            _bodyArray.add(_body);
        }

        int random = Math.abs(rand.nextInt());
        JSONObject _messageRequest = new JSONObject();
        _messageRequest.put("MsgBody", _bodyArray);
        _messageRequest.put("Random", random);
        _messageRequest.put("From_Account", "1");
        _messageRequest.put("GroupId", groupid);

        //OfflinePushInfo beggin
        JSONObject offlinePushInfo = new JSONObject();
        offlinePushInfo.put("Title", title);
        offlinePushInfo.put("Desc", message);

        //  2022/3/19
        offlinePushInfo.put("PushFlag", pushFlag);
        JSONObject extInfo = new JSONObject();
        extInfo.put("group_id", groupid);
        extInfo.put("group_name", groupName);
        extInfo.put("from_user_id", "1");
        extInfo.put("from_user_name", "1");
        extInfo.put("pushType", "999999");

        offlinePushInfo.put("Ext", extInfo.toJSONString());

        _messageRequest.put("OfflinePushInfo", offlinePushInfo);
        //OfflinePushInfo end

        String _requestJson = _messageRequest.toJSONString();
        logger.info("the im push message request body:" + _requestJson);

        String _responseBody = "";
        if (isSendmessage()) {
            ResponseEntity<String> _callReponse = restTemplate.postForEntity(_url, _messageRequest, String.class);
            _responseBody = _callReponse.getBody();
            logger.info("the im push message response body:" + _responseBody);
            GroupResponse _groupResponse = JSON.parseObject(_responseBody, GroupResponse.class);
            String _actionStatus = _groupResponse.getActionStatus();
            if (_actionStatus.equals("OK")) {
                isSuccess = true;
            }

            String _requestString = JSON.toJSONString(_postData);
            _repository.insertIMHistory("发送群消息", _url, _requestString, _responseBody);
        }
        return _responseBody;
    }
    public String sendGrooupCommonMessage2(int pushFlag, String groupName, String groupid, String title, String message, String messageType, String extData,
                                          JSONObject extJsonObject,
                                          JSONObject custExtJsonObject, int userid) {

        boolean isSuccess = false;
        int _adminId = getAdminId();
        long _sdkid = getSDKId();
        String _winKeyPath = getWinKeyPath();
        String _linuxKeyPath = getLinuxKeyPath();


        String strUserid = Integer.toString(userid);
        String _method = getGroupUrl() + getCommonGroupMessageMethod();
        String _sig = SignatureManager.getSignatureAdv(_sdkid, _winKeyPath, _linuxKeyPath, Integer.toString(_adminId), _imConfig.getSigType(), _imConfig.getSecuretKey());
        String _url = getUrl(_sig, _method, _adminId);

        //请求数据
        JSONObject _postData = new JSONObject();
        _postData.put("GroupId", groupid);
        _postData.put("Content", "message");

        /*
        *
        *    "MsgContent": {
        "Data": "发送消息的内容",  --群聊的内容
        "Desc": "消息的类型",      --消息的类型：text,file
        "Ext": "url",              --额外的数据，file类型就是文件的url
        "Sound": "dingdong.aiff"
    }
        * */
        JSONObject _contentText = new JSONObject();
        _contentText.put("Text", message);

        JSONObject _bodyText = new JSONObject();
        _bodyText.put("MsgType", "TIMTextElem");
        _bodyText.put("MsgContent", _contentText);

        JSONArray _bodyArray = new JSONArray();
        _bodyArray.add(_bodyText);

        if (custExtJsonObject != null) {
            JSONObject _extContent = new JSONObject();
            _extContent.put("Data", message);
            _extContent.put("Desc", "customermsg");
            _extContent.put("Ext", custExtJsonObject.toJSONString());

            JSONObject _extBody = new JSONObject();
            _extBody.put("MsgType", "TIMCustomElem");
            _extBody.put("MsgContent", _extContent);

            _bodyArray.add(_extBody);
        }

        if (extJsonObject != null) {
            JSONObject _extContent = new JSONObject();
            _extContent.put("Data", message);
            _extContent.put("Desc", "customer");
            _extContent.put("Ext", extJsonObject.toJSONString());

            JSONObject _extBody = new JSONObject();
            _extBody.put("MsgType", "TIMCustomElem");
            _extBody.put("MsgContent", _extContent);

            _bodyArray.add(_extBody);
        }

        JSONObject _content = new JSONObject();
        _content.put("Data", message);
        _content.put("Desc", "file");
        _content.put("Ext", extData);

        JSONObject _body = new JSONObject();
        _body.put("MsgType", "TIMCustomElem");
        _body.put("MsgContent", _content);
        if (messageType.equals("file")) {
            _bodyArray.add(_body);
        }

        int random = Math.abs(rand.nextInt());
        JSONObject _messageRequest = new JSONObject();
        _messageRequest.put("MsgBody", _bodyArray);
        _messageRequest.put("Random", random);
        _messageRequest.put("From_Account", "1");
        if (messageType.equals("file")) {
            if(message.indexOf("上传了文件")!=-1)
            _messageRequest.put("From_Account", strUserid);
        }
        _messageRequest.put("GroupId", groupid);

        //OfflinePushInfo beggin
        JSONObject offlinePushInfo = new JSONObject();
        offlinePushInfo.put("Title", title);
        offlinePushInfo.put("Desc", message);

        //  2022/3/19
        offlinePushInfo.put("PushFlag", pushFlag);
        JSONObject extInfo = new JSONObject();
        extInfo.put("group_id", groupid);
        extInfo.put("group_name", groupName);
        extInfo.put("from_user_id", "1");
        extInfo.put("from_user_name", "1");
        extInfo.put("pushType", "999999");

        offlinePushInfo.put("Ext", extInfo.toJSONString());

        _messageRequest.put("OfflinePushInfo", offlinePushInfo);
        //OfflinePushInfo end

        String _requestJson = _messageRequest.toJSONString();
        logger.info("the im push message request body:" + _requestJson);

        String _responseBody = "";
        if (isSendmessage()) {
            ResponseEntity<String> _callReponse = restTemplate.postForEntity(_url, _messageRequest, String.class);
            _responseBody = _callReponse.getBody();
            logger.info("the im push message response body:" + _responseBody);
            GroupResponse _groupResponse = JSON.parseObject(_responseBody, GroupResponse.class);
            String _actionStatus = _groupResponse.getActionStatus();
            if (_actionStatus.equals("OK")) {
                isSuccess = true;
            }

            String _requestString = JSON.toJSONString(_postData);
            _repository.insertIMHistory("发送群消息", _url, _requestString, _responseBody);
        }
        return _responseBody;
    }

    public long getSDKId() {
        return _imConfig.getSdkappid();
    }

    public String getWinKeyPath() {
        return _imConfig.getKeypath_windows();
    }

    public String getLinuxKeyPath() {
        return _imConfig.getKeypath_linux();
    }

    public int getAccessType() {
        return _imConfig.getAccounttype();
    }

    public String getRootUrl() {
        return _imConfig.getRooturl();
    }

    public String getGroupUrl() {
        return _imConfig.getGroupurl();
    }

    public String getAccountUrl() {
        return _imConfig.getAccounturl();
    }

    public String getAccountImportMethod() {
        return _imConfig.getAccountimport();
    }

    public String getCreateGroupMethod() {
        return _imConfig.getCreategroup();
    }

    public String getKickMethod() {
        return _imConfig.getKick();
    }

    public String getDestroyGroupMethod() {
        return _imConfig.getDestroyGroup();
    }

    public String getAddGroupMemberMethod() {
        return _imConfig.getAddGroupMember();
    }

    public String getDeleteGroupMemberMethod() {
        return _imConfig.getDeleteGroupMember();
    }

    public String getCommonGroupMessageMethod() {
        return _imConfig.getCommonGroupMessage();
    }

    private int getAdminId() {
        return _imConfig.getAdminid();
    }

    private boolean isSendmessage() {
        return _imConfig.isSendmessage();
    }

    public int getSigType() {
        return _imConfig.getSigType();
    }

    public String getSecuretKey() {
        return _imConfig.getSecuretKey();
    }
    //

    //更新聊天组
    public boolean updataeIMGroup(String groupid, String groupName, String groupIntroduction, int userid) {
        boolean isSuccess = false;
        try {

            int _adminId = getAdminId();
            long _sdkid = getSDKId();
            String _winKeyPath = getWinKeyPath();
            String _linuxKeyPath = getLinuxKeyPath();

            String strUserid = Integer.toString(userid);
            String _method = getGroupUrl() + getUpdateGroupMethod();

            String _sig = SignatureManager.getSignatureAdv(_sdkid, _winKeyPath, _linuxKeyPath, Integer.toString(_adminId), _imConfig.getSigType(), _imConfig.getSecuretKey());
            String _url = getUrl(_sig, _method, _adminId);

            //请求数据
            JSONObject _postData = new JSONObject();
            _postData.put("GroupId", groupid);
            _postData.put("Name", groupName);
            _postData.put("Introduction", groupIntroduction);

            logger.info("the request body:" + _postData.toString());
            ResponseEntity<String> _callReponse = restTemplate.postForEntity(_url, _postData, String.class);
            String _responseBody = _callReponse.getBody();
            logger.info("the response body:" + _responseBody);
            GroupResponse _groupResponse = JSON.parseObject(_responseBody, GroupResponse.class);
            String _actionStatus = _groupResponse.getActionStatus();
            if (_actionStatus.equals("OK")) {
                isSuccess = true;
            }

            new Thread(() -> {
                String _requestString = JSON.toJSONString(_postData);
                _repository.insertIMHistory("更新聊天组名称", _url, _requestString, _responseBody);
            }).start();

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return isSuccess;
    }

    public String getUpdateGroupMethod() {
        // return _imConfig.getDestroyGroup();

        return "modify_group_base_info";
    }


}
